﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows;

namespace Zero.UControl.Base.Helper.Base.UAdorner
{
    internal class SelectionService
    {

        private readonly Canvas _canvas;
        private readonly DrawingTool _tool;
        private readonly Dictionary<UIElement, SelectionAdorner> _map = new();
        public IEnumerable<UIElement> Selected => _map.Keys;
        public SelectionService(Canvas c, DrawingTool t)
        {
            _canvas = c; 
            _tool = t;
        }

        public void Attach(UIElement el, bool additive = false)
        {
            if (!additive) 
                ClearAll();
            if (_map.ContainsKey(el))
                return;
            var layer = AdornerLayer.GetAdornerLayer(_canvas);
            var ad = new SelectionAdorner(el, _tool);
            layer?.Add(ad);
            _map[el] = ad;
            el.IsManipulationEnabled = true;
        }
        public void Set(IEnumerable<UIElement> els)
        {
            ClearAll();
            foreach (var el in els)
                Attach(el, true);
        }

        public void AddRange(IEnumerable<UIElement> els)
        {
            foreach (var el in els)
                Attach(el, true);
        }

        public void Detach(UIElement el)
        {
            if (!_map.Remove(el, out var ad))
                return;
            var layer = AdornerLayer.GetAdornerLayer(_canvas);
            layer?.Remove(ad);
        }

        private void ClearAll()
        {
            foreach (var ad in _map.Values)
            {
                var layer = AdornerLayer.GetAdornerLayer(_canvas);
                layer?.Remove(ad);
            }
            _map.Clear();
        }

    }
}
